package com.shwread.android.ui.page;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.ciko.code.bean.PerformanceAddress;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.Req.AttendBackReq;
import com.ciko.code.http.Req.AttendReachReq;
import com.ciko.code.http.Req.CheckUserHaveReachReq;
import com.ciko.code.http.Req.GetAttendByUserEty;
import com.ciko.code.http.Req.GetAttendByUserReq;
import com.ciko.code.http.Req.GetMonthAttendCountEty;
import com.ciko.code.http.Req.QryPerformanceAddressListEty;
import com.ciko.code.http.Req.QryPerformanceAddressListReq;
import com.ciko.code.type.AttendType;
import com.humanres.activity.ResCheckActivity;
import com.humanres.activity.ResGradeActivity;
import com.humanres.activity.ResMoreActivity;
import com.humanres.activity.ResOtherActivity;
import com.mywork.WorkUIKit;
import com.mywork.activity.PollSurveyActivity;
import com.mywork.activity.ResRemarkActivity;
import com.mywork.activity.WorkMeetingActivity;
import com.mywork.activity.WorkPlaneActivity;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.FieldAttendanceActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.ReLocationActivity;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.GridViewCustom;
import com.shwread.android.ui.dialog.AttendOutDialog;
import com.shwread.android.ui.dialog.AttendOutDialog.SimpleOutListener;
import com.shwread.android.ui.dialog.CommonDialog;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.httpsdk.util.NetUtil;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.MyWorkGridViewBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;


/**
 * 项目名称：association
 * 包名称：com.shwread.android.ui.page
 * 类描述：
 * 创建人： wayne
 * 创建时间 2016/1/28 2:51.
 */
public class MyWorkPage
        extends
        AbstractUIPage<MainActivity>
        implements
        View.OnClickListener,
        AMapLocationListener
{
	
	private static MyWorkPage		 instance;
									 
	private TextView				 tvTitle;
	private ImageView				 ivPersion;
	private Button					 btnBack;
									 
	// private View rect_checkRes;
	// private View rect_leaveRes;
	//private View rect_outRes;
	//private View rect_jiaBanRes;
	//    private View rect_planRes;
	//    private View rect_expenseRes;
	//    private View rect_gradeRes;
	//    private View rect_meetingRes;
	//    private View rect_voteRes;
	//    private View rect_otherRes;
	private View					 rect_QiandaoCheck;
	private View					 rect_QiantuiCheck;
									 
	//    private Button ivQiandaoCheck;
	//    private Button ivQiantuiCheck;
	private TextView				 tvQiandaoDay;
	private TextView				 tvNoQiandaoDay;
	private TextView				 dateToDay;
	//    private TextView timeToDay;
	private TextView				 tvAttendDay;
	private TextView				 tvAttendStatus;
	private TextView				 tvQiandaoTimeCheck;
	private TextView				 tvQiandaoStateCheck;
	private TextView				 tvQiantuiTimeCheck;
	private TextView				 tvQiantuiStateCheck;
	private TextView				 tvAdressCheck;
	private ImageView				 remarksIcon1;
	private ImageView				 remarksIcon2;
	private LoadingView				 loadingView;
	private LinearLayout			 loadFail;
	private ScrollView				 workSv;
									 
	private AMapLocationClient		 locationClient		 = null;
	private AMapLocationClientOption locationOption		 = null;
	private AMapLocation			 location			 = null;
	private boolean					 needManulLocation	 = false;
	//许克烽
	private GridViewCustom			 grid_view;
	ArrayList<MyWorkGridViewBean>	 datas;
									 
	QryPerformanceAddressListEty	 addressListEty;
	private GetAttendByUserEty		 getAttendByUser;
									 
	private String					 reason				 = "";
	private CommonDialog			 gpsDialog;
	private ProgressDialog			 progressDialog;
	private boolean					 isLocated			 = false;//判断已定位
	private boolean					 isGetaddressListEty = false;//判断已获取后台返回值addressListEty
	private int						 CLICKTYPE			 = 0;	 //1点击的是签退，2是签到
	private Thread					 thread;
	private CommonDialog			 dialog;
	private AMapLocation             aMapLocation;

	public static MyWorkPage getInstance(MainActivity t) {
		if (instance == null) {
			instance = new MyWorkPage(t);
		}else {
			instance.setActivity(t);
		}
		return instance;
	}
	public MyWorkPage(MainActivity mainActivity) {
		super(mainActivity);
	}
	
	@Override
	public <E extends Activity> View createView(E e, int i) {
		
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.fragment_res, null);
		
		initGpsDialog();
		QyreaderPerferencesUtil util = QyreaderPerferencesUtil.getInstance(context, DefaultConsts.FIRST_TAG);
		if (!Util.gpsIsOpen(bActivity) && util.getShowGpsOpen())
		{
			//gpsDialog.show();
			util.setShowGpsOpen(false);
		}
		initTitleBar();
		initView();
		initDatas();
		initListener();
		initAdapter();
		
		        startLocation();
		
		//获取太保账号信息
		//		doRequestHttp(new UserLoginReq(WorkUIKit.getAccount()));
		new Thread(new Runnable()
		{
			@Override
			public void run() {
				BaseBusinessActivity.uiHandler.postDelayed(new Runnable()
				{
					@Override
					public void run() {
						CheckUserHaveReach();
						//获取签到范围
						doRequestHttp(new QryPerformanceAddressListReq(WorkUIKit.getUser().getBranchNo()));
						//                        startLocation();
					}
				}, 1000);
			}
		}).start();
		return curMyView;
	}
	
	private void initGpsDialog() {
		gpsDialog = new CommonDialog(bActivity)
		{
			@Override
			protected void clickOk(View v) {
				super.clickOk(v);
				gpsDialog.dismiss();
			}
			
			@Override
			protected void clickCancel(View v) {
				super.clickCancel(v);
				Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				bActivity.startActivityForResult(intent, 0);
			}
		};
		gpsDialog.setTvText("打开“GPS”以便准确获取当前位置");
		gpsDialog.setButtonText("取消");
		gpsDialog.setButtonCancelText("设置");
	}
	
	void startLocation() {
		aMapLocation = null;
		locationClient = new AMapLocationClient(bActivity);
		locationOption = new AMapLocationClientOption();
		// 设置定位模式为高精度模式
		locationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
		// 设置定位监听
		locationClient.setLocationListener(this);
		// 设置定位参数
		locationOption.setNeedAddress(true);
		locationOption.setInterval(1000 * 60);
		
		locationClient.setLocationOption(locationOption);
		// 启动定位
		locationClient.startLocation();
	}
	
	private void initAdapter() {
		grid_view.setAdapter(new GridViewAdapter());
//		grid_view.setParameter(datas.size() / 2);
	}
	
	private void initTitleBar() {
		tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
		tvTitle.setText("我的工作");
		ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
		ivPersion.setVisibility(View.VISIBLE);
		btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.GONE);
	}
	
	protected void initView() {
		Activity activity = bActivity;
		while (activity.getParent() != null) {
			  activity = activity.getParent();
		}

		progressDialog = new ProgressDialog(activity);
		progressDialog.setCancelable(true);
		progressDialog.setMessage("正在定位");
		dialog = new CommonDialog(bActivity)
		{
			@Override
			protected void clickOk(View v) {
				super.clickOk(v);
			}
		};
		dialog.setTvText("获取当前位置失败，请稍后重试");
		dialog.setButtonText("确定");
		dialog.setBtnCancelGone();
		//加载超时判断
		thread = new Thread(new Runnable()
		{
			@Override
			public void run() {
				BaseBusinessActivity.uiHandler.postDelayed(new Runnable()
				{
					@Override
					public void run() {
						if (aMapLocation != null && addressListEty == null)
						{
							dialog.setTvText("获取考勤范围失败，请稍后重试");
							progressDialog.dismiss();
							dialog.show();
							stopLocation();
							dialog.setTvText("获取当前位置失败，请稍后重试");
						}
					}
				}, 10000);
			}
		});
		// rect_checkRes = curMyView.findViewById(R.id.rect_checkRes);
		// rect_leaveRes = curMyView.findViewById(R.id.rect_leaveRes);
		//rect_outRes = curMyView.findViewById(R.id.rect_outRes);
		//rect_jiaBanRes = curMyView.findViewById(R.id.rect_jiabanRes);
		//        rect_planRes = curMyView.findViewById(R.id.rect_planeWork);
		//        rect_expenseRes = curMyView.findViewById(R.id.rect_expenseRes);
		//        rect_gradeRes = curMyView.findViewById(R.id.rect_gradeRes);
		//        rect_meetingRes = curMyView.findViewById(R.id.rect_meetingRes);
		//        rect_voteRes = curMyView.findViewById(R.id.rect_voteRes);
		//        rect_otherRes = curMyView.findViewById(R.id.rect_otherRes);
		
		//        this.tvAdressCheck = (TextView) curMyView.findViewById(R.id.tvAdressCheck);
		tvAttendDay = (TextView) curMyView.findViewById(R.id.tvKaoqinDialy);
		tvAttendStatus = (TextView) curMyView.findViewById(R.id.tvKaoqinStatus);
		this.tvQiantuiStateCheck = (TextView) curMyView.findViewById(R.id.tvQiantuiStateCheck);
		this.tvQiantuiTimeCheck = (TextView) curMyView.findViewById(R.id.tvQiantuiTimeCheck);
		this.tvQiandaoStateCheck = (TextView) curMyView.findViewById(R.id.tvQiandaoStateCheck);
		this.tvQiandaoTimeCheck = (TextView) curMyView.findViewById(R.id.tvQiandaoTimeCheck);
		//        this.timeToDay = (TextView) curMyView.findViewById(R.id.timeToDay);
		this.dateToDay = (TextView) curMyView.findViewById(R.id.dateToDay);
		//        this.tvNoQiandaoDay = (TextView) curMyView.findViewById(R.id.tvNoQiandaoDay);
		//        this.tvQiandaoDay = (TextView) curMyView.findViewById(R.id.tvQiandaoDay);
		this.rect_QiandaoCheck = (View) curMyView.findViewById(R.id.llQiandaoCheck);
		this.rect_QiantuiCheck = (View) curMyView.findViewById(R.id.llQiantuiCheck);
		this.remarksIcon1 = (ImageView) curMyView.findViewById(R.id.remarks_icon1);
		this.remarksIcon2 = (ImageView) curMyView.findViewById(R.id.remarks_icon2);
		
		grid_view = (GridViewCustom) curMyView.findViewById(R.id.grid_view);
		grid_view.setSelector(new ColorDrawable(Color.TRANSPARENT));
		
		loadingView = (LoadingView) curMyView.findViewById(R.id.loading_my_work);
		loadingView.setLoadingAnim(R.anim.home_progress);
		loadingView.changeLoadingStatus(0);
		loadFail = (LinearLayout) curMyView.findViewById(R.id.ll_none_things);
		workSv = (ScrollView) curMyView.findViewById(R.id.my_work_sv);
		CheckUserHaveReach();
	}
	
	void initDatas() {
		Calendar calendar = Calendar.getInstance(Locale.CANADA);
		
		dateToDay.setText(getChineseWeekday(calendar) + " " + getChineseDate(calendar));
		//        timeToDay.setText("当前时间：" + calendar.get(Calendar.HOUR_OF_DAY) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)));
		
		datas = new ArrayList<MyWorkGridViewBean>();
		MyWorkGridViewBean mg;
		
		mg = new MyWorkGridViewBean("考勤管理", R.drawable.icon_res_check, "check");
		datas.add(mg);
		
		mg = new MyWorkGridViewBean("请假管理", R.drawable.icon_res_leave, "leave");
		datas.add(mg);
		
		mg = new MyWorkGridViewBean("出差管理", R.drawable.icon_res_out, "out");
		datas.add(mg);
		
		mg = new MyWorkGridViewBean("加班管理", R.drawable.icon_res_jiaban, "jiaban");
		datas.add(mg);
		
		mg = new MyWorkGridViewBean("工作计划", R.drawable.icon_work_plane, "plane");
		datas.add(mg);

		mg = new MyWorkGridViewBean("报销审批", R.drawable.icon_res_expense, "expense");
		datas.add(mg);

		mg = new MyWorkGridViewBean("绩效查询", R.drawable.icon_res_grade, "grade");
		datas.add(mg);
//
		mg = new MyWorkGridViewBean("会议助手", R.drawable.icon_res_meeting2, "meeting2");
		datas.add(mg);

		mg = new MyWorkGridViewBean("投票调研", R.drawable.icon_res_vote, "vote");
		datas.add(mg);

		mg = new MyWorkGridViewBean("知识文库", R.drawable.icon_res_other2, "other2");
		datas.add(mg);
		
		mg = new MyWorkGridViewBean("外勤签到", R.drawable.icon_field_att, "att");
		datas.add(mg);

		mg = new MyWorkGridViewBean("公文传阅", R.drawable.icon_doc_read, "document");
		datas.add(mg);
		
	}
	
	protected void initListener() {
		// rect_checkRes.setOnClickListener(this);
		// rect_leaveRes.setOnClickListener(this);
		//rect_outRes.setOnClickListener(this);
		//rect_jiaBanRes.setOnClickListener(this);
		//        rect_planRes.setOnClickListener(this);
		//        rect_expenseRes.setOnClickListener(this);
		//        rect_gradeRes.setOnClickListener(this);
		//        rect_meetingRes.setOnClickListener(this);
		//        rect_voteRes.setOnClickListener(this);
		//        rect_otherRes.setOnClickListener(this);
		
		ivPersion.setOnClickListener(this);
		
		rect_QiantuiCheck.setOnClickListener(this);
		rect_QiandaoCheck.setOnClickListener(this);
		loadFail.setOnClickListener(this);
	}
	
	@Override
	public View updateView(int i, ITaskResult iTaskResult) {
		return null;
	}
	
	@Override
	public void notifyView(int i, Bundle bundle) {
		String remark;
		switch (i) {
			case DefaultConsts.MSG_LOCATION_START:
				
				break;
			case DefaultConsts.MSG_LOCATION_STOP:
				
				break;
			case DefaultConsts.MSG_LOCATION_FINISH:
				stopLocation();
				if (needManulLocation)
				{
				
				}
				break;
			case DefaultConsts.MSG_OUT_REMARK:
				remark = bundle.getString("content");
				reason = "签到不成功/出差";
				doRequestHttp(new AttendReachReq(AttendType.out.getValue(), location.getAddress(), location.getLongitude(), location.getLatitude(), remark));
				break;
			case DefaultConsts.MSG_LEAVE_REMARK:
				remark = bundle.getString("content");
				reason = "签到不成功/请假";
				doRequestHttp(new AttendReachReq(AttendType.leave.getValue(), location.getAddress(), location.getLongitude(), location.getLatitude(), remark));
				break;
			case DefaultConsts.MSG_OTHER_REMARK:
				remark = bundle.getString("content");
				reason = "签到不成功/其它";
				doRequestHttp(new AttendReachReq(AttendType.other.getValue(), location.getAddress(), location.getLongitude(), location.getLatitude(), remark));
				break;
			case DefaultConsts.MSG_OUT_BACKREMARK:
				reason = "签退不成功/出差";
				remark = bundle.getString("content");
				doRequestHttp(new AttendBackReq(AttendType.out.getValue(), location.getAddress(), location.getLongitude(), location.getLatitude(), remark));
				break;
			case DefaultConsts.MSG_LEAVE_BACKREMARK:
				reason = "签退不成功/请假";
				remark = bundle.getString("content");
				doRequestHttp(new AttendBackReq(AttendType.leave.getValue(), location.getAddress(), location.getLongitude(), location.getLatitude(), remark));
				break;
			case DefaultConsts.MSG_OTHER_BACKREMARK:
				reason = "签退不成功/其他";
				remark = bundle.getString("content");
				doRequestHttp(new AttendBackReq(AttendType.other.getValue(), location.getAddress(), location.getLongitude(), location.getLatitude(), remark));
				break;
		}
	}
	
	@Override
	public int enter(IUIPage<?> iuiPage) {
		CheckUserHaveReach();
		//		//获取签到范围
		//		doRequestHttp(new QryPerformanceAddressListReq(WorkUIKit.getUser().getBranchNo()));
		//		startLocation();
		//		isLocated = false;
		//		isGetaddressListEty = false;
		//		progressDialog.show();
		return 0;
	}
	
	void CheckUserHaveReach() {
		//        loadingView.setVisibility(View.VISIBLE);
		//        loadFail.setVisibility(View.GONE);
		//        workSv.setVisibility(View.GONE);
		//检查今天是否已经签到
		doRequestHttp(new CheckUserHaveReachReq());
		
		////      获取该月所有的记录
		//        doRequestHttp(new GetMonthAttendCountReq());
		doRequestHttp(new GetAttendByUserReq());

	}
	
	@Override
	public int leave(IUIPage<?> iuiPage) {
		if (null != locationClient)
		{
			/**
			 * 如果AMapLocationClient是在当前Activity实例化的，
			 * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
			 */
			locationClient.onDestroy();
			locationClient = null;
			locationOption = null;
		}
		return 0;
	}

	public void setRefresh()
	{
		doRequestHttp(new CheckUserHaveReachReq());
	}
	
	@Override
	public void setStatus(int i) {
	
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			//            case R.id.rect_checkRes:
			//                intent2Acticity(ResCheckActivity.class);
			//                break;
			//            case R.id.rect_leaveRes:
			////                intent2Acticity(ResLeaveActivity.class);
			//                gotoMoreActivity("请假管理");
			//                break;
			//            case R.id.rect_outRes:
			//                gotoMoreActivity("出差管理");
			////                intent2Acticity(ResOutActivity.class);
			//                break;
			//            case R.id.rect_jiabanRes:
			//                gotoMoreActivity("加班管理");
			////                intent2Acticity(ResOverWorkActivity.class);
			//                break;
			//            case R.id.rect_planeWork:
			//                Intent intent = new Intent(bActivity, WorkPlaneActivity.class);
			//                if (null != location) intent.putExtra("address", location.getAddress());
			//                context.startActivity(intent);
			//                break;
			//            case R.id.rect_expenseRes:
			//                //TODO 报销审批
			//                gotoMoreActivity("报销审批");
			//                break;
			//            case R.id.rect_gradeRes:
			//                intent2Acticity(ResGradeActivity.class);
			//                break;
			//            case R.id.rect_meetingRes:
			//                intent2Acticity(WorkMeetingActivity.class);
			//                break;
			//            case R.id.rect_voteRes:
			//                //TODO 投票调研
			//                intent2Acticity(PollSurveyActivity.class);
			//                break;
			//            case R.id.rect_otherRes:
			//                intent2Acticity(ResOtherActivity.class);
			//                break;
			case R.id.ll_none_things:
				CheckUserHaveReach();
				break;
			case R.id.common_header_persion:
				bActivity.goPersonalActivity();
				break;
			case R.id.llQiandaoCheck:
				addressListEty = null;
				isGetaddressListEty = false;
				if (!NetUtil.isNetworkConnected(bActivity))
				{
					new NoNetDialog(bActivity).show();
					return;
				}
				if (!Util.gpsIsOpen(bActivity))
				{
					gpsDialog.show();
					return;
				}
				if (WorkUIKit.getUser().getBranchNo().equals(""))
				{
					Util.showToast(bActivity, R.string.params_less_tip);
					return;
				}
				CLICKTYPE = 2;
				progressDialog.show();
				doRequestHttp(new QryPerformanceAddressListReq(WorkUIKit.getUser().getBranchNo()));
				thread.run();
				isLocated = false;
				startLocation();
				
				break;
			case R.id.llQiantuiCheck:
				addressListEty = null;
				isGetaddressListEty = false;
				if (!NetUtil.isNetworkConnected(bActivity))
				{
					new NoNetDialog(bActivity).show();
					return;
				}
				if (!Util.gpsIsOpen(bActivity))
				{
					gpsDialog.show();
					return;
				}
				if (WorkUIKit.getUser().getBranchNo().equals(""))
				{
					Util.showToast(bActivity, R.string.params_less_tip);
					return;
				}
				CLICKTYPE = 1;
				progressDialog.show();
				doRequestHttp(new QryPerformanceAddressListReq(WorkUIKit.getUser().getBranchNo()));
				thread.run();
				isLocated = false;
				startLocation();
				
				break;
				
		}
	}
	////31.1506170000,116.9610680000
	private void clickQiantui() {
		if (!checkLocationValid())
		{
			dialog = new CommonDialog(bActivity){
				@Override
				protected void clickOk(View v) {
					new AttendOutDialog(bActivity, new SimpleOutListener()
					{
						@Override
						public void out() {
							Intent intent = new Intent(bActivity, ResRemarkActivity.class);
							intent.putExtra("title", "出差");
							bActivity.startActivityForResult(intent, Const.ATTEND_QUIT);
						}

						@Override
						public void leave() {
							Intent intent = new Intent(bActivity, ResRemarkActivity.class);
							intent.putExtra("title", "请假");
							bActivity.startActivityForResult(intent, Const.ATTEND_QUIT);
						}

						@Override
						public void other() {
							Intent intent = new Intent(bActivity, ResRemarkActivity.class);
							intent.putExtra("title", "其他");
							bActivity.startActivityForResult(intent, Const.ATTEND_QUIT);
						}
					}).show();
					dialog.dismiss();
				}

				@Override
				protected void clickClose(View v) {
					dialog.dismiss();
				}
				@Override
				protected void clickCancel(View v) {
					dialog.dismiss();
					Intent intent = new Intent(bActivity, ReLocationActivity.class);
					bActivity.startActivity(intent);
				}
			};
			dialog.setButtonText("选择原因");//----ok
			dialog.setCloseBtnVisiable();
			dialog.setButtonCancelText("重新定位");//--------cancel
			dialog.setTvText("当前定位位置不在考勤范围内，请重新定位或选择原因!");
			dialog.show();
			//Util.showToast(bActivity, "签退");
			//doRequestHttp(new AttendBackReq(4, location.getAddress(), location.getLongitude(), location.getLatitude(), ""));
		}
		else
		{
			
			String time1 = addressListEty.getEndTime();
			String time2 = DateUtil.getFormatedDateTime(System.currentTimeMillis());
			int min1 = Integer.valueOf(time1.substring(0, 2)) * 60 + Integer.valueOf(time1.substring(3, 5));
			int min2 = Integer.valueOf(time2.substring(0, 2)) * 60 + Integer.valueOf(time2.substring(3, 5));
			
			if (min1 - 10 > min2 && checkLocationValid())
			{
				CommonDialog commonDialog = new CommonDialog(bActivity)
				{
					@Override
					protected void clickOk(View v) {
						super.clickOk(v);
						doRequestHttp(new AttendBackReq(4, location.getAddress(), location.getLongitude(), location.getLatitude(), ""));
					}
				};
				commonDialog.setTvText("现在是早退时间，是否确定签退？");
				commonDialog.show();
			}
			else
			{
				doRequestHttp(new AttendBackReq(4, location.getAddress(), location.getLongitude(), location.getLatitude(), ""));
			}
		}
	}

	private void clickQiandao() {
		if (checkLocationValid())
		{
			//Util.showToast(bActivity, "签到");
			reason = "";
			doRequestHttp(new AttendReachReq(AttendType.normal.getValue(), location.getAddress(), location.getLongitude(), location.getLatitude(), ""));
		}
		else
		{
			dialog = new CommonDialog(bActivity){
				@Override
				protected void clickOk(View v) {
					new AttendOutDialog(bActivity, new SimpleOutListener()
					{
						@Override
						public void out() {
							Intent intent = new Intent(bActivity, ResRemarkActivity.class);
							intent.putExtra("title", "出差");
							bActivity.startActivityForResult(intent, Const.ATTEND_QUIT);
						}

						@Override
						public void leave() {
							Intent intent = new Intent(bActivity, ResRemarkActivity.class);
							intent.putExtra("title", "请假");
							bActivity.startActivityForResult(intent, Const.ATTEND_QUIT);
						}

						@Override
						public void other() {
							Intent intent = new Intent(bActivity, ResRemarkActivity.class);
							intent.putExtra("title", "其他");
							bActivity.startActivityForResult(intent, Const.ATTEND_QUIT);
						}
					}).show();
					dialog.dismiss();
				}

				@Override
				protected void clickClose(View v) {
					dialog.dismiss();
				}
				@Override
				protected void clickCancel(View v) {
					dialog.dismiss();
					Intent intent = new Intent(bActivity, ReLocationActivity.class);
					bActivity.startActivity(intent);
				}
			};
			dialog.setButtonText("选择原因");//----ok
			dialog.setCloseBtnVisiable();
			dialog.setButtonCancelText("重新定位");//--------cancel
			dialog.setTvText("当前定位位置不在考勤范围内，请重新定位或选择原因");
			dialog.show();
		}
	}
	//	31.1506170000,116.9610680000
	boolean checkLocationValid() {
		boolean result = false;
		if (null == addressListEty)
		{
			doRequestHttp(new QryPerformanceAddressListReq(WorkUIKit.getUser().getBranchNo()));
			
		}
		else
		{
			if (!addressListEty.getPerformaceList().isEmpty())
			{
				for (PerformanceAddress address : addressListEty.getPerformaceList())
				{
					String dis = getDistance(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), address.getLat(), address.getLon());
//					String dis = getDistance(String.valueOf(31.1506170000), String.valueOf(116.9610680000), address.getLat(), address.getLon());
//					LogUtil.d("location", dis);
//					if ((Long.parseLong(dis) * 1000 - Long.parseLong(address.getDistance())) < 0)
						if ((Double.valueOf(dis) * 1000 - Double.valueOf(address.getDistance())) < 0)
					{
						result = true;
						break;
					}
					
				}
			}
			
		}
		LogUtil.d("location", "" + result);
		return result;
	}
	
	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}
	
	private static double EARTH_RADIUS = 6378.137;
	
	/**
	 * 根据两个位置的经纬度，来计算两地的距离（单位为KM）
	 * 参数为String类型
	 *
	 * @param lat1Str
	 *            用户经度
	 * @param lng1Str
	 *            用户纬度
	 * @param lat2Str
	 *            商家经度
	 * @param lng2Str
	 *            商家纬度
	 * @return
	 */
	public String getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
		Double lat1 = Double.parseDouble(lat1Str);
		Double lng1 = Double.parseDouble(lng1Str);
		Double lat2 = Double.parseDouble(lat2Str);
		Double lng2 = Double.parseDouble(lng2Str);
		
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double difference = radLat1 - radLat2;
		double mdifference = rad(lng1) - rad(lng2);
		double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2)));
		distance = distance * EARTH_RADIUS;
//		distance = Math.round(distance * 10000) / 10000;
		String distanceStr = distance + "";

//		distanceStr = distanceStr.substring(0, distanceStr.indexOf("."));
		
		return distanceStr;
	}
	
	private void gotoMoreActivity(String title) {
		Intent intent = new Intent(getContext(), ResMoreActivity.class);
		intent.putExtra("title", title);
		bActivity.startActivity(intent);
	}
	
	public static void destroy() {
		if (instance != null)
		{
			instance.dispose();
			instance = null;
		}
	}
	
	@Override
	public void onResponseFail(String tag, int resultCode) {
		super.onResponseFail(tag, resultCode);
		if (resultCode == 4001)
		{
			boolean hasQiandao = true;
			
			//            ivQiandaoCheck.setBackgroundDrawable(hasQiandao ? getDrawable(com.mywork.R.drawable.icon_qiandao_pressed) : getDrawable(com.mywork.R.drawable.icon_qiandao_normal));
			//            ivQiantuiCheck.setBackgroundDrawable(hasQiandao ? getDrawable(com.mywork.R.drawable.icon_qiantui_normal) : getDrawable(com.mywork.R.drawable.icon_qiantui_pressed));
			//            ivQiandaoCheck.setClickable(!hasQiandao);
			//            ivQiantuiCheck.setClickable(hasQiandao);
			//
			//            ivQiandaoCheck.setText(hasQiandao ? "已签到" : "签到");
			//            ivQiantuiCheck.setText(hasQiandao ? "签退" : "已签退");
			
			rect_QiantuiCheck.setVisibility(hasQiandao ? View.VISIBLE : View.GONE);
			rect_QiandaoCheck.setVisibility(hasQiandao ? View.GONE : View.VISIBLE);
		}
		else if (resultCode == 8000)
		{
			Calendar calendar = Calendar.getInstance(Locale.CANADA);
			
			tvAttendDay.setText(bActivity.getString(R.string.attend_daily, getChineseDate(calendar)));
			tvAttendStatus.setText(bActivity.getString(R.string.empty));
			
			boolean hasQiandao = false;
			rect_QiantuiCheck.setVisibility(hasQiandao ? View.VISIBLE : View.GONE);
			rect_QiandaoCheck.setVisibility(hasQiandao ? View.GONE : View.VISIBLE);
		}
		else
		{
			loadingView.setVisibility(View.GONE);
//			loadFail.setVisibility(View.VISIBLE);
//			workSv.setVisibility(View.GONE);
		}
		
		if (tag.equals("QryPerformanceAddressListReq"))
		{
			progressDialog.dismiss();
			CLICKTYPE = 0;
		}
	}
	
	@Override
	public void onResponseSuccess(final BaseResponse<?> response, String tag) {
		super.onResponseSuccess(response, tag);
		
		switch (tag) {
			case "CheckUserHaveReachReq":
				
				boolean hasQiandao = false;
				
				//                ivQiandaoCheck.setBackgroundDrawable(hasQiandao ? getDrawable(com.mywork.R.drawable.icon_qiandao_pressed) : getDrawable(com.mywork.R.drawable.icon_qiandao_normal));
				//                ivQiantuiCheck.setBackgroundDrawable(hasQiandao ? getDrawable(com.mywork.R.drawable.icon_qiantui_normal) : getDrawable(com.mywork.R.drawable.icon_qiantui_pressed));
				//                ivQiandaoCheck.setClickable(!hasQiandao);
				//                ivQiantuiCheck.setClickable(hasQiandao);
				//
				//                ivQiandaoCheck.setText(hasQiandao ? "已签到" : "签到");
				//                ivQiantuiCheck.setText(hasQiandao ? "签退" : "已签退");
				rect_QiantuiCheck.setVisibility(View.GONE);
				rect_QiandaoCheck.setVisibility(View.VISIBLE);
				tvQiandaoTimeCheck.setText("未签到");
				remarksIcon1.setVisibility(View.GONE);
				tvQiandaoStateCheck.setVisibility(View.GONE);
				tvQiantuiTimeCheck.setText("未签退");
				remarksIcon2.setVisibility(View.GONE);
				tvQiantuiStateCheck.setVisibility(View.GONE);
				rect_QiantuiCheck.setEnabled(true);
				rect_QiantuiCheck.setBackgroundResource(R.drawable.icon_qiantui);
				break;
			case "GetMonthAttendCountReq":
				GetMonthAttendCountEty getMonthAttendCountEty = (GetMonthAttendCountEty) response.getReturnObject();
				//                tvQiandaoDay.setText(getMonthAttendCountEty.getAttendHaveDays() + "");
				//                tvNoQiandaoDay.setText(getMonthAttendCountEty.getAttendNoneDays() + "");
				break;
			case "GetAttendByUserReq":
				BaseBusinessActivity.uiHandler.post(new Runnable()
				{
					@Override
					public void run() {
						loadingView.setVisibility(View.GONE);
						loadFail.setVisibility(View.GONE);
						workSv.setVisibility(View.VISIBLE);
						final GetAttendByUserEty getAttendByUserEty = (GetAttendByUserEty) response.getReturnObject();
						getAttendByUser = getAttendByUserEty;
						tvAttendDay.setText(bActivity.getString(R.string.attend_daily, getAttendByUserEty.getAttendDay()));
						if (Util.isNotEmpty(getAttendByUserEty.getAttendTypeName()))
						{
							//签到状态
							if (!getAttendByUserEty.getAttendType().equals("0"))//0=正常上班 1=出差 2=请假 3=其它
							{
								remarksIcon1.setVisibility(View.VISIBLE);
								tvQiandaoStateCheck.setVisibility(View.VISIBLE);
								if (getAttendByUserEty.getAttendType().equals("1"))
								{
									reason = "签到不成功/出差";
								}
								else if (getAttendByUserEty.getAttendType().equals("2"))
								{
									reason = "签到不成功/请假";
								}
								else if (getAttendByUserEty.getAttendType().equals("3"))
								{
									reason = "签到不成功/其它";
								}
								if (Util.isNotEmpty(reason))
				                                             tvQiandaoStateCheck.setText(reason);
								else
				                                             tvQiandaoStateCheck.setText(getAttendByUserEty.getReachTypeName());
								remarksIcon1.setOnClickListener(new View.OnClickListener()
								{
									@Override
									public void onClick(View v) {
										Intent intent = new Intent(bActivity, ResRemarkActivity.class);
										intent.putExtra("type", getAttendByUserEty.getAttendType());
										intent.putExtra("content", getAttendByUserEty.getTakeRemark());
										bActivity.startActivity(intent);
									}
								});
							}
							else
							{
								tvQiandaoStateCheck.setVisibility(View.VISIBLE);
								tvQiandaoStateCheck.setText(getAttendByUserEty.getReachTypeName().equals("正常") ? "签到成功" : getAttendByUserEty.getReachTypeName());
							}
						}
				        //				else
				        //				{
				        //					tvQiandaoStateCheck.setVisibility(View.VISIBLE);
				        //					tvQiandaoStateCheck.setText("签到成功");
				        //				}
				        
						//签到签退时间
						if (Util.isNotEmpty(getAttendByUserEty.getReachType()))
						{
							tvQiandaoTimeCheck.setText(bActivity.getString(R.string.attend_time, Util.getFormatTimeforSecond(getAttendByUserEty.getReachTime())));
						}
						if (Util.isNotEmpty(getAttendByUserEty.getQuitType()))
						{
							tvQiantuiTimeCheck.setText(bActivity.getString(R.string.qiantui_time, Util.getFormatTimeforSecond(getAttendByUserEty.getQuitTime())));
						}
						
						//签退状态
						if (Util.isNotEmpty(getAttendByUserEty.getQuitAttendTypeName()))
						{
							if (!getAttendByUserEty.getQuitAttendType().equals("4"))//4=正常下班 1=出差 2=请假 3=其它
							{
								remarksIcon2.setVisibility(View.VISIBLE);
								tvQiantuiStateCheck.setVisibility(View.VISIBLE);
								if (getAttendByUserEty.getQuitAttendType().equals("1"))
								{
									reason = "签退不成功/出差";
								}
								else if (getAttendByUserEty.getQuitAttendType().equals("2"))
								{
									reason = "签退不成功/请假";
								}
								else if (getAttendByUserEty.getQuitAttendType().equals("3"))
								{
									reason = "签退不成功/其它";
								}
								if (Util.isNotEmpty(reason))
				                                             tvQiantuiStateCheck.setText(reason);
								else
				                                             tvQiantuiStateCheck.setText(getAttendByUserEty.getQuitAttendTypeName());
								remarksIcon2.setOnClickListener(new View.OnClickListener()
								{
									@Override
									public void onClick(View v) {
										Intent intent = new Intent(bActivity, ResRemarkActivity.class);
										intent.putExtra("type", getAttendByUserEty.getQuitAttendType());
										intent.putExtra("content", getAttendByUserEty.getBackRemark());
										bActivity.startActivity(intent);
									}
								});
							}
							else
							{
								tvQiantuiStateCheck.setVisibility(View.VISIBLE);
								tvQiantuiStateCheck.setText(getAttendByUserEty.getQuitTypeName().equals("正常") ? "签退成功" : getAttendByUserEty.getQuitTypeName());
							}
							
							rect_QiantuiCheck.setBackgroundResource(R.drawable.qiantui_bg);
							rect_QiantuiCheck.setEnabled(false);
						}
					}
				});
				
				break;
			case "QryPerformanceAddressListReq":
				addressListEty = (QryPerformanceAddressListEty) response.getReturnObject();
				isGetaddressListEty = true;
				if (isLocated)
				{
					progressDialog.dismiss();
					if (CLICKTYPE == 1)
					{
						clickQiantui();
						CLICKTYPE = 0;
					}
					else if (CLICKTYPE == 2)
					{
						clickQiandao();
						CLICKTYPE = 0;
					}
				}
				break;
			case "AttendReachReq":
				String msg1 = (String) response.getReturnObject();
				Util.showToast(bActivity, msg1);
				//刷新页面
				CheckUserHaveReach();
				break;
			case "AttendBackReq":
				String msg2 = (String) response.getReturnObject();
				Util.showToast(bActivity, msg2);
				//刷新页面
				CheckUserHaveReach();
				break;
				
		}
	}
	
	Drawable getDrawable(int resId) {
		return context.getResources().getDrawable(resId);
	}
	
	public static String getChineseWeekday(Calendar paramCalendar) {
		switch (paramCalendar.get(Calendar.DAY_OF_WEEK)) {
			case 1:
				return "星期日";
			case 2:
				return "星期一";
			case 3:
				return "星期二";
			case 4:
				return "星期三";
			case 5:
				return "星期四";
			case 6:
				return "星期五";
			case 7:
				return "星期六";
		}
		return "未知";
	}
	
	public static String getChineseDate(Calendar paramCalendar) {
		int i = paramCalendar.get(Calendar.YEAR);
		int j = paramCalendar.get(Calendar.MONTH);
		int k = paramCalendar.get(Calendar.DAY_OF_MONTH);
		StringBuffer localStringBuffer = new StringBuffer();
		localStringBuffer.append(i);
		localStringBuffer.append("/");
		localStringBuffer.append(j + 1);
		localStringBuffer.append("/");
		localStringBuffer.append(k);
		return localStringBuffer.toString();
	}
	
	@Override
	public void onLocationChanged(AMapLocation aMapLocation) {
		this.aMapLocation = aMapLocation;
		if (null != aMapLocation)
		{
			Message msg = Message.obtain();
			msg.obj = aMapLocation;
			msg.what = DefaultConsts.MSG_LOCATION_FINISH;
			bActivity.getUIHandler().sendMessage(msg);
			//            Logger.i(getLocationStr(aMapLocation));
			this.location = aMapLocation;
			isLocated = true;
			if (isGetaddressListEty)
			{
				progressDialog.dismiss();
				if (CLICKTYPE == 1)
				{
					clickQiantui();
					CLICKTYPE = 0;
				}
				else if (CLICKTYPE == 2)
				{
					clickQiandao();
					CLICKTYPE = 0;
				}
			}
		}
		
		else
		{
			progressDialog.dismiss();
			CLICKTYPE = 0;
			dialog.show();
		}
	}
	
	void stopLocation() {
		if (null != locationClient)
		{
			locationClient.stopLocation();
		}
	}
	
	/**
	 * 根据定位结果返回定位信息的字符串
	 *
	 * @param location
	 * @return
	 */
	public synchronized static String getLocationStr(AMapLocation location) {
		if (null == location) { return null; }
		StringBuffer sb = new StringBuffer();
		//errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
		if (location.getErrorCode() == 0)
		{
			sb.append("定位成功" + "\n");
			sb.append("定位类型: " + location.getLocationType() + "\n");
			sb.append("经    度    : " + location.getLongitude() + "\n");
			sb.append("纬    度    : " + location.getLatitude() + "\n");
			sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
			sb.append("提供者    : " + location.getProvider() + "\n");
			
			if (location.getProvider().equalsIgnoreCase(android.location.LocationManager.GPS_PROVIDER))
			{
				// 以下信息只有提供者是GPS时才会有
				sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
				sb.append("角    度    : " + location.getBearing() + "\n");
				// 获取当前提供定位服务的卫星个数
				sb.append("星    数    : " + location.getSatellites() + "\n");
			}
			else
			{
				// 提供者是GPS时是没有以下信息的
				sb.append("国    家    : " + location.getCountry() + "\n");
				sb.append("省            : " + location.getProvince() + "\n");
				sb.append("市            : " + location.getCity() + "\n");
				sb.append("城市编码 : " + location.getCityCode() + "\n");
				sb.append("区            : " + location.getDistrict() + "\n");
				sb.append("区域 码   : " + location.getAdCode() + "\n");
				sb.append("地    址    : " + location.getAddress() + "\n");
				sb.append("兴趣点    : " + location.getPoiName() + "\n");
			}
		}
		else
		{
			//定位失败
			sb.append("定位失败" + "\n");
			sb.append("错误码:" + location.getErrorCode() + "\n");
			sb.append("错误信息:" + location.getErrorInfo() + "\n");
			sb.append("错误描述:" + location.getLocationDetail() + "\n");
		}
		return sb.toString();
	}
	
	class GridViewAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			return datas.size();
		}
		
		@Override
		public Object getItem(int position) {
			return datas.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null)
			{
				convertView = LayoutInflater.from(getContext()).inflate(R.layout.my_work_gridview_child, null);
				holder = new ViewHolder();
				holder.img_view = (ImageView) convertView.findViewById(R.id.img_view);
				holder.txt_view = (TextView) convertView.findViewById(R.id.txt_view);
				holder.lin_layout = (LinearLayout) convertView.findViewById(R.id.lin_layout);
				holder.lin_layout.setTag(datas.get(position).getType());
				
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.txt_view.setText(datas.get(position).getName());
			holder.img_view.setBackgroundResource(datas.get(position).getSource());
			holder.lin_layout.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v) {
					String type = datas.get(position).getType();
					switch (type) {
						case "check":
							intent2Acticity(ResCheckActivity.class, datas.get(position).getName());
							break;
						case "leave":
							gotoMoreActivity("请假管理");
							break;
						case "out":
							gotoMoreActivity("出差管理");
							break;
						case "jiaban":
							gotoMoreActivity("加班管理");
							break;
						case "plane":
							Intent intent = new Intent(bActivity, WorkPlaneActivity.class);
							if (null != location)
			                                      intent.putExtra("address", location.getAddress());
							intent.putExtra("title", datas.get(position).getName());
							context.startActivity(intent);
							break;
						case "expense":
							gotoMoreActivity("报销审批");
							break;
						case "grade":
							intent2Acticity(ResGradeActivity.class, datas.get(position).getName());
							break;
						case "meeting2":
							intent2Acticity(WorkMeetingActivity.class, datas.get(position).getName());
							break;
						case "vote":
							intent2Acticity(PollSurveyActivity.class, datas.get(position).getName());
							break;
						case "other2":
							intent2Acticity(ResOtherActivity.class, datas.get(position).getName());
							break;
							
						case "att":
							intent2Acticity(FieldAttendanceActivity.class, datas.get(position).getName());
						case "document":
							intent2Acticity(ResOtherActivity.class, datas.get(position).getName());
							break;
					}
				}
			});
			return convertView;
		}
	}
	
	class ViewHolder
	{
		ImageView	 img_view;
		TextView	 txt_view;
		LinearLayout lin_layout;
	}
}
